#!/usr/bin/env python2
#-*- coding: utf-8 -*-

import os
import web
import json
import traceback

from sqlalchemy.orm.exc import NoResultFound
from Umpweb.base import render_jinja
from Umpweb.db import api as db_api
from Umpweb.common import utils, config

from Umpweb.base import session, _, render_jinja

render = render_jinja('static/templates/vgroup', encoding='utf-8',)


class VGroupList:
    def GET(self):
        web.header("Content-Type", "text/plain")
        return render.vgroup_list()


class VGroupCreate:

    def GET(self):
        x = web.input()
        volumes = db_api.volume_get_all()

        reload(config)
        protocols = config.protocols
        cluster = db_api.cluster_get(1)
        if cluster.is_nfs:
            protocols.append('nfs')

        return render.vgroup_create(volumes=volumes, protocols=protocols)

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        values = dict(**web.input())
        body = {"VGroupCreate":{'params':values}}
        return utils.web_return(body)


class VGroupDelete:

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        body = {"VGroupDelete":{'params':{'id':x.get('id').strip()}}}
        return utils.web_return(body)

        
class VGroupUpdate:

    def GET(self):
        x = web.input()
        vgroup = db_api.vgroup_get(x['id'])
        vgroup_volumes = db_api.volume_get_with_vgroup(x['id'])
        vgroup_volume_ids = [x.id for x in vgroup_volumes ]
        volumes = db_api.volume_get_all()
        return render.vgroup_update(volumes=volumes, 
                vgroup=vgroup,
                vgroup_volume_ids=vgroup_volume_ids)

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        values = dict(**web.input())
        body = {"VGroupUpdate": {'params': values}}
        return utils.web_return(body)


class VGroupRollback:

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        values = dict(**web.input())
        body = {"VGroupRollback": {'params': values}}
        return utils.web_return(body)


class VGroupClone:

    def GET(self):
        x = web.input()
        vgroup = db_api.vgroup_get(x.get('id'))
        return render.vgroup_clone(vgroup=vgroup)

    def POST(self):
        x = web.input()
        web.header("Content-Type", "application/json")
        values = dict(**web.input())

        body = {"VGroupClone": {'params': values}}
        return utils.web_return(body)


class GridVGroup:
    def POST(self):
        web_input = web.input()
        filters = {}
        page, total, records, rows = \
                utils.grid_rows_query(db_api.vgroup_table, web_input, filters=filters)

        for vgroup in rows:
            volumes = db_api.volume_get_with_vgroup(vgroup.id)
            volume_names = [x.name for x in volumes ]
            vgroup.show_volume_name = ",".join(volume_names)
            
        cells = ['id', 'name', 'show_volume_name','username','created_at']

        rows_json = utils.grid_json(
                page, total, records, rows, 'id', cells)
        web.header("Content-Type", "application/json")
        return rows_json

class GetVGroups:

    def GET(self):
        x = web.input()
        web.header("Content-Type", "application/json")
        vgroups = db_api.vgroup_get_with_volume(x.volume_id)
        vgroups = [vgroup.__dict__ for vgroup in vgroups]
        return json.dumps(vgroups)

class GridVGroupPolicy:
    def POST(self):
        web_input = web.input()
        filters = {}
        page, total, records, rows = \
                utils.grid_rows_query(db_api.vgroup_policy_table, web_input, filters=filters)


        cells = ['id', 'name', 'username','created_at','operation']

        rows_json = utils.grid_json(
                page, total, records, rows, 'id', cells)
        web.header("Content-Type", "application/json")
        return rows_json

class VGroupPolicyList:
    def GET(self):
        return render.vgroup_policy_list()

class VGroupTask:

    def GET(self):
        x = web.input()
        volume_id = x.get('volume_id')
        volume = db_api.volume_get(volume_id)
        count = unit = ''
        if volume.vgroup_time:
            count_unit = volume.vgroup_time.split('-')[0]
            count = count_unit[:-1]
            unit = count_unit[-1]
        volume.vgroup_cycle = None
        if unit == 'd' :
            volume.vgroup_cycle = "%s天" % count
        if unit == 'm' :
            volume.vgroup_cycle = "%s分钟" % count
        if unit == 'h' :
            volume.vgroup_cycle = "%s小时" % count
        return render.vgroup_task(volume=volume)

    def POST(self):
        x = web.input()
        web.header("Content-Type", "application/json")
        values = dict(**web.input())
        body = {"VGroupTask": {'params': values}}
        return utils.web_return(body)


class VGroupPolicyCreate:

    def GET(self):
        return render.vgroup_policy_create()

    def POST(self):
        x = web.input()
        web.header("Content-Type", "application/json")
        values = {
            'count':x.count.strip(),
            'unit': x.get('unit').strip(),
            'name':x.get('name')
           }

        body = {"VGroupPolicyCreate": {'params': values}}
        return utils.web_return(body)


class VGroupPolicyDelete:

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        body = {"VGroupPolicyDelete":{'params':{'id':x.get('id').strip()}}}
        return utils.web_return(body)


class VGroupConsistency:
    def GET(self):
        return render.vgroup_consistency()


class GridVolumeCGSnap:
    def GET(self):
        web_input = web.input()
        vgroup_id = web_input.get('vgroup_id')
        protocol = web_input.get('protocol')
            
        filters = {'status':'normal'}
        if vgroup_id == 'null':
            filters['vgroup_id'] = None
        elif vgroup_id:
            filters['vgroup_id'] = vgroup_id

        if protocol:
            filters['protocol'] = protocol

    
        page, total, records, rows = \
                utils.grid_rows_query(db_api.volume_table, web_input, filters=filters)

        cells = ['id', 'path', '']
        rows_json = utils.grid_json(
                page, total, records, rows, 'id', cells)
        web.header("Content-Type", "application/json")
        return rows_json
        

